package br.edu.utfpr.backupTools.rmi;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;

import javax.swing.JOptionPane;

import br.edu.utfpr.backupTools.model.pojo.Configuracao;
import br.edu.utfpr.backupTools.util.Mensagem;
import br.edu.utfpr.backupTools.view.action.AbstractListCommand;
import br.edu.utfpr.backupTools.view.action.configuracao.ListarConfiguracao;
import br.edu.utfpr.backupTools.view.telas.principal.JanelaPrincipal;
import br.edu.utfpr.comum.RmiProvider;

/**
 * Singleton responsavel por manter a conexao rmi com o servidor
 * 
 * @see RmiProvider
 * @author Luan Malaguti Reffatti
 */
public class ClienteRmi {
	
	private static RmiProvider provider;
	private static ClienteRmi instance;
	private static String ip;
	
	public ClienteRmi(){
	}
	
	public static final ClienteRmi getInstance(){
		if(instance == null)
		{
			if(getIp() == null){
				Mensagem.show(JanelaPrincipal.getComponent(), "Não foi possivel conectar com o servidor", JOptionPane.ERROR_MESSAGE);
				return null;
			}
			
			instance = new ClienteRmi();
			
			try {
				provider = (RmiProvider) Naming.lookup("rmi://" + ClienteRmi.ip + ":1099/BackupToolsService");
			
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (NotBoundException e) {
				e.printStackTrace();
			}
		}
		return instance;
	}
	
	public RmiProvider provider(){
		return provider;
	}
	
	private static String getIp(){
		AbstractListCommand<Configuracao> action = new ListarConfiguracao();
		ClienteRmi.ip = action.execute().get(0).getIp();
		return ClienteRmi.ip == null ? null : ClienteRmi.ip;
	}
}
